package com.haisen.core.aspect;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.Properties;

/**
 * 针对tk.mybatis不会自动更新updatetime，建立里拦截器来实现
 *
 */
@Intercepts({
        @Signature(type = Executor.class, method = DataChangeLastTimeInterceptor.METHOD_UPDATE, args = {
                MappedStatement.class, Object.class})})
public class DataChangeLastTimeInterceptor implements Interceptor {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    public static final String METHOD_UPDATE = "update";
    public static final String[] METHOD_SET_DATA_CHANGE_LAST_TIME = new String[]{"setUpdateTime", "setUpdate_Time"};

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
       // logger.info("数据库更新操作，拦截器生效");
        String methodName = invocation.getMethod().getName();
        if (methodName.equalsIgnoreCase(DataChangeLastTimeInterceptor.METHOD_UPDATE)) {
            Object parameter = invocation.getArgs()[1];
            Date empty = null;
            try {
                for (String s : METHOD_SET_DATA_CHANGE_LAST_TIME) {
                    ReflectionUtils.callMethod(parameter, s, true, empty);
                }
            } catch (Exception e) {
                logger.warn("setUpdateTime error:" + e.getMessage() + ",class:" + parameter.getClass());
            }
        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object o) {
        return Plugin.wrap(o, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
